<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Java多线程(实现多线程) |  Yolin
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.png" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="Yolin" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Java多线程-实现多线程" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Java多线程(实现多线程)
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/08/14/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E5%AE%9E%E7%8E%B0%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="article-date">
  <time datetime="2020-08-14T05:58:02.000Z" itemprop="datePublished">2020-08-14</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">3分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h2 id="一、实现多线程"><a href="#一、实现多线程" class="headerlink" title="一、实现多线程"></a>一、实现多线程</h2><h3 id="1-1-进程"><a href="#1-1-进程" class="headerlink" title="1.1 进程"></a>1.1 进程</h3><p><strong>是系统进行资源分配和调用的独立单位</strong>（通俗讲就是操作系统中执行的一个子程序，包含了三部分：虚拟CPU、代码、数据）</p>
<ul>
<li>是系统进行资源分配和调用的独立单位</li>
<li>每一个进程都有它自己的内存空间和系统资源</li>
</ul>
<h3 id="1-2-线程"><a href="#1-2-线程" class="headerlink" title="1.2 线程"></a>1.2 线程</h3><p><strong>是进程中的单个顺序控制流，是一条执行路径</strong></p>
<ul>
<li><strong>单线程</strong>：一个进程只有一条执行路径</li>
<li><strong>多线程</strong>：一个进程有多条执行路径</li>
</ul>
<h3 id="1-3-多线程的实现方式"><a href="#1-3-多线程的实现方式" class="headerlink" title="1.3 多线程的实现方式"></a>1.3 多线程的实现方式</h3><h4 id="方式1：继承Thread类"><a href="#方式1：继承Thread类" class="headerlink" title="方式1：继承Thread类"></a>方式1：继承Thread类</h4><a id="more"></a>
<ol>
<li>定义一个类继承自Thread类</li>
<li>在定义的类中重写run()方法</li>
<li>创建自定义类的对象</li>
<li>启动线程</li>
</ol>
<p>注意：</p>
<ul>
<li>run()方法是用来封装被线程执行的代码的相当于普通方法的调用</li>
<li>start()方法用来启动线程，然后由JVM调用此线程的run()方法</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-12_20-03-26.jpg" alt=""></p>
<p>因为我们不知道输出的内容分别属于那个线程，所以还需要设置和获取线程名称</p>
<h3 id="1-4设置和获取线程名称"><a href="#1-4设置和获取线程名称" class="headerlink" title="1.4设置和获取线程名称"></a>1.4设置和获取线程名称</h3><p>Thread类中设置和获取线程名称的方法</p>
<ul>
<li>void setName(String name):将此线程的名称改为等于参数name</li>
<li>String getName():返回此线程的名称</li>
<li>通过构造方法也可以设置线程名称</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-12_21-30-32.jpg" alt=""></p>
<blockquote>
<p>currentThread()<br>返回对当前正在执行的线程对象的引用。 </p>
</blockquote>
<p>获取main方法所在线程名称</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.out.println(Thread.currentThread().getName()); <span class="comment">//main</span></span><br></pre></td></tr></table></figure>

<h3 id="1-5-线程调度"><a href="#1-5-线程调度" class="headerlink" title="1.5 线程调度"></a>1.5 线程调度</h3><p>线程有两种调度模式</p>
<ul>
<li><strong>分时调度模型</strong>：所有线程轮流使用CPU的使用权，平均分配每个线程占用CPU的时间片</li>
<li>**抢占式调度模型：优先让优先级高的线程使用CPU，如果优先级相同，会随机选择，优先级高的线程获取的CPU时间片相对多一些</li>
</ul>
<p>Java使用抢占式调度模式</p>
<p>假如计算机只有一个CPU，那么CPU在某一个时刻只能执行一条指令，线程只有得到CPU时间片，也就是使用权，才能执行指令。所以说多线程程序的执行是有随机性的。</p>
<h4 id="如何自己设置优先级"><a href="#如何自己设置优先级" class="headerlink" title="如何自己设置优先级"></a>如何自己设置优先级</h4><p>Thread类中设置和获取线程优先级的方法</p>
<ul>
<li>public final int getPriority():返回此线程的优先级</li>
<li>public final void setPriority(int newPriority):更改此线程的优先级</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> yolin;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">demo1</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		MyThread mt1=<span class="keyword">new</span> MyThread();</span><br><span class="line">		MyThread mt2=<span class="keyword">new</span> MyThread();</span><br><span class="line">		MyThread mt3=<span class="keyword">new</span> MyThread();</span><br><span class="line">		mt1.setName(<span class="string">"florence"</span>);</span><br><span class="line">		mt2.setName(<span class="string">"yolin"</span>);</span><br><span class="line">		mt3.setName(<span class="string">"db"</span>);</span><br><span class="line"><span class="comment">//		System.out.println(mt1.getPriority());//5 默认值</span></span><br><span class="line"><span class="comment">//		System.out.println(mt2.getPriority());//5</span></span><br><span class="line"><span class="comment">//		System.out.println(mt3.getPriority());//5</span></span><br><span class="line">		System.out.println(Thread.MAX_PRIORITY);<span class="comment">//最大值10</span></span><br><span class="line">		System.out.println(Thread.MIN_PRIORITY);<span class="comment">//最小值1</span></span><br><span class="line">		System.out.println(Thread.NORM_PRIORITY);<span class="comment">//默认5</span></span><br><span class="line">		</span><br><span class="line">		mt1.setPriority(<span class="number">5</span>);</span><br><span class="line">		mt2.setPriority(<span class="number">10</span>);</span><br><span class="line">		mt3.setPriority(<span class="number">1</span>);</span><br><span class="line">		</span><br><span class="line">		mt1.start();</span><br><span class="line">		mt2.start();</span><br><span class="line">		mt3.start();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>线程优先级高仅仅表示线程获取的CPU时间片的几率高，但是要在次数比较多，或多次运行的时候才能看到想要的效果</p>
<h3 id="1-6-线程控制"><a href="#1-6-线程控制" class="headerlink" title="1.6 线程控制"></a>1.6 线程控制</h3><table>
<thead>
<tr>
<th>方法名</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>static void sleep(long millis)</td>
<td>使当前正在执行的线程停留（暂停执行）指定的毫秒数</td>
</tr>
<tr>
<td>void join()</td>
<td>等待这个线程死亡</td>
</tr>
<tr>
<td>void setDaemon(boolean on)</td>
<td>将此线程标记为守护线程，当运行的线程都是守护线程时，Java虚拟机将退出</td>
</tr>
</tbody></table>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-13_20-40-49.jpg" alt=""></p>
<hr>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-13_21-08-16.jpg" alt=""></p>
<hr>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-14_10-42-54.jpg" alt=""></p>
<h3 id="1-7-线程生命周期"><a href="#1-7-线程生命周期" class="headerlink" title="1.7 线程生命周期"></a>1.7 线程生命周期</h3><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-14_11-18-46.jpg" alt=""></p>
<h3 id="1-8-多线程的实现方式"><a href="#1-8-多线程的实现方式" class="headerlink" title="1.8 多线程的实现方式"></a>1.8 多线程的实现方式</h3><p>方式2：实现Runnable接口  </p>
<ul>
<li>定义一个类Runnable_实现Runnable接口</li>
<li>在Runnable_类中重写run()方法</li>
<li>创建Runnable_类的对象</li>
<li>创建Thread类的对象，把Runnable_对象作为构造方法的参数</li>
<li>启动线程</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-14_14-04-55.jpg" alt=""></p>
<p>多线程的实现方案有两种</p>
<ul>
<li>继承Thread类</li>
<li>实现Runnable接口</li>
</ul>
<p>相比继承Thread类，<strong>实现Runnable接口的好处</strong></p>
<ul>
<li>避免了Java单继承的局限性</li>
<li>适合多个相同程序的代码去处理同一个资源的情况，把线程和程序的代码、数据邮箱分离，较好的体现了面向对象的设计思想</li>
</ul>

      
      <!-- reward -->
      
    </div>
      <!-- copyright -->
      
    <footer class="article-footer">
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E7%BA%BF%E7%A8%8B/" rel="tag">线程</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E8%BF%9B%E7%A8%8B/" rel="tag">进程</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/08/16/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Java多线程(线程同步)
          
        </div>
      </a>
    
    
      <a href="/2020/08/12/%E4%BB%8E%E6%B5%81%E5%BC%80%E5%A7%8B%E7%9A%84IO%E4%B8%96%E7%95%8C%E7%94%9F%E6%B4%BB-%E5%9B%9B/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">从流开始的IO世界生活(四)</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020-2021
        张金
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
        <img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/beian.png">
        <a href="https://beian.miit.gov.cn"  style="color:#f72b07" target="_blank">陕ICP备20002449号</a>
      </li>

    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Yolin"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/playlist">歌单</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/video">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友情链接</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['肠断月明红豆蔻,','月似当时,','人似当时否？'],
    startDelay: 1500,
    typeSpeed: 200,
    loop: true,
    backSpeed: 40,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>